<template xmlns:el-table="http://www.w3.org/1999/html" style="width: 913px">
  <div class="common-layout">
    <el-container>
      <el-header style="padding: 0;margin: 0">
        <el-affix :offset="0">
          <div id="headDiv">
            <div>
              <el-button type="warning" size="large" style="margin-left: 40px" @click="home()" round>
                <el-icon>
                  <House/>
                </el-icon>
                首页
              </el-button>
            </div>
            <div :hidden="userLogin">
              <span style="color: #626262;margin-right: 20px">您好! 请购物！</span>
              <el-button type="primary" size="large" @click="$router.push('goods')" round>全部商品</el-button>
              <el-button type="primary" size="large" @click="toShoppingCar()" round>购物车</el-button>
              <el-button size="large" type="primary" @click="toOrder()" round>个人订单</el-button>
              <el-button size="large" type="primary" @click="$router.push('user')" round>个人信息</el-button>
              <el-button size="large" type="primary" @click="$router.push('returnOrder')" round>
                退款订单管理
              </el-button>
              <el-button size="large" type="primary" @click="$router.push('userMoney')" round>预存款管理</el-button>
              <el-button size="large" type="danger" style="margin-right: 20px" @click="exitUser()" round>退出登录
              </el-button>
            </div>
          </div>
        </el-affix>
      </el-header>
      <div style="font-size: 30px;margin: 20px 200px">
        <a href="#" style="color:#545454;text-decoration: none;">LO<span style="color: #c4c4c4">V</span><span>O</span> |
          朗沃商城</a>
      </div>
      <el-main style="display: flex;justify-content: center;padding: 0;margin: 0">
        <div id="bodyDiv">
          <div
              style="height: 60px;display: flex;justify-content: space-between;align-items: center;border-top:1px #101010 solid">
            <div class="block">
              <el-cascader
                  v-model="value"
                  :options="options"
                  :props="{ label:'typeName',value:'typeNo',children:'typeVos',expandTrigger: 'hover' }"
                  placeholder="请选择商品类型"
                  @change="handleChange()"></el-cascader>
              <el-button type="primary" size="large" @click="cleanType()" round>清除类型</el-button>
            </div>
            <div style="margin-right: 55px">
              <el-input v-model="input3" placeholder="输入您想搜索的内容" style="width: 600px;height: 40px"
                        size="large">
                <template #append>
                  <el-button @click="search()">
                    <el-icon>
                      <Search/>
                    </el-icon>
                    <span style="color: #c72121">搜索</span>
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>
          <div>
            <basic-container>
              <el-row>
                <el-col v-for="(product, index) in productList" :key="product" :span="5" :offset="index > 0 ? 1:1"
                        style="margin-left: 45px">
                  <el-card :body-style="{ padding: '0 19px'}"
                           style="background-color: white;color: #181818;margin-top: 20px;height: 450px">
                    <el-image :src="actionUrl+product.goodsPic" style="width: 250px;height: 250px;margin-top: 10px">
                    </el-image>
                    <div>
                      <div>
                        <p style="color:#2f2f2f;margin: 0;font-size: 20px">产品名称：{{ product.goodsName }}</p>
                        <h3 style="margin: 5px;color: #c72121">价格:{{ product.sellPrice }}</h3>
                        <h5 style="margin: 5px;color: gray"><span>类型:{{ product.goodsType }}</span><span
                            style="margin-left:60px">折扣:{{ product.discount }}</span></h5>
                        <h5 style="margin: 5px;color: gray"><span>描述:{{ product.des }}</span></h5>
                        <div style="margin-top: 10px;display: flex;justify-content: space-between">
                          <el-button @click="addShopping(product)">
                            加入购物车
                          </el-button>
                          <el-button type="primary" @click="buyProduct(product)">
                            购买
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
              <div id="pagination">
                <el-pagination
                    style="background-color: white"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page.currentPage"
                    :page-sizes="[12,24,36,48]"
                    :page-size="page.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.totalCount">
                </el-pagination>
              </div>
            </basic-container>
          </div>
        </div>
      </el-main>
    </el-container>
  </div>
  <!-- 加入购物车 -->
  <el-dialog v-model="showShoppingCar">
    <h1>商品名称:{{ product.goodsName }}</h1>
    <div style="display: flex;justify-content: end;margin-top: 20px">
      <span style="color: #ff1a1a;font-size: 20px">折后价：{{ (product.sellPrice * product.discount).toFixed(2) }}</span>
    </div>
    <div style="display: flex;justify-content: end;margin-top: 20px">
      <span style="color: black;font-size: 15px">商品规格：{{ product.goodsSize }}</span>
    </div>
    <template #footer>
      <el-button type="primary" @click="addShoppingCar(product)">加入购物车</el-button>
      <el-button @click="closeDiv">取消</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showCheckout">
    <h1>商品名称:{{ product.goodsName }}</h1>
    <el-select v-model="selectAddress" placeholder="请选择收货地址" @change="changeAddress" style="width: 300px">
      <el-option
          v-for="item in addressOptions"
          :key="item.addressId"
          :label="item.receiverRegion+' '+item.receiverAddress"
          :value="item.addressId"
      >
      </el-option>
    </el-select>
    <el-input-number v-model="buyNum" :min="1" :max="99"/>
    <div style="display: flex;justify-content: space-around;margin-top: 20px">
      <span style="color: black;font-size: 20px">商品总价：{{moneyVo.totalMoney}}</span>
      <span style="color: green;font-size: 20px">折后价：{{moneyVo.totalPrice}}</span>
      <span style="color: orange;font-size: 20px">预存款支付折后价：{{moneyVo.preTotalPrice}}</span>
    </div>
    <template #footer>
      <el-button type="primary" @click="pay(1)">预存款支付</el-button>
      <el-button type="primary" @click="pay(0)">支付宝支付</el-button>
      <el-button @click="closeDiv">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";

export default {
  data() {
    return {
      buyNum:1,
      value: [],
      options: [],
      //分页
      page: {
        //每页显示条数
        pageSize: 12,
        //当前页码
        currentPage: 1,
        //总记录数
        totalCount: 0,
      },
      userToken: "",
      input3: "",
      unLogin: false,
      userLogin: false,
      productList: [],
      actionUrl: "/picture/face/",
      product: {},
      buy:{},
      productType: "",
      showCheckout: false,
      showShoppingCar: false,
      config: {},
      selectAddress: '',
      ackAddress: {},
      addressOptions: [],
      moneyVo:{}
    }
  },
  created() {
    this.selectAll();
    this.queryAddress();
    this.queryType();
  },
  methods: {
    cleanType(){
      this.value=[]
      this.selectAll()
    },
    queryType(){
      axios.get("/api/goods/queryType",null).then(res=>{
        console.log(res.data)
        this.options=res.data
      })
    },
    handleChange() {
      console.log(this.value);
      let param = new URLSearchParams();
      param.append("typeNo",this.value[this.value.length-1])
      param.append("curPage", this.page.currentPage);
      param.append("pageSize", this.page.pageSize);
      console.log(param)
      axios.post("/api/goods/queryGoodsByType", param).then(res => {
        console.log(res.data)
        this.productList = res.data.records;
        this.page.totalCount = res.data.total;
      })
    },
    selectAll() {
      let param = new URLSearchParams();
      param.append("curPage", this.page.currentPage);
      param.append("pageSize", this.page.pageSize);
      console.log(param)
      axios.post("/api/goods/readGoodsList", param).then(res => {
        console.log(res.data)
        this.productList = res.data.records;
        this.page.totalCount = res.data.total;
      })
    },
    search() {
      this.page.currentPage = 1;
      let param = new URLSearchParams();
      param.append("curPage", this.page.currentPage);
      param.append("pageSize", this.page.pageSize);
      param.append("des", this.input3);
      axios.post("/api/goods/readGoodsListByDes", param).then(res => {
        console.log(res.data)
        this.productList = res.data;
      })
    },
    //分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      //设置每页显示条数
      this.page.pageSize = val;
      // 查询所有商品
      this.selectAll();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      //重新设置当前页
      this.page.currentPage = val;
      // 查询所有商品
      this.selectAll();
    },
    //选择产品类型
    changeType() {
    },
    //返回首页
    home() {
      this.$router.push("app")
    },

    //退出登录
    exitUser() {
      sessionStorage.clear();
      this.$router.push("newLogin");
    },
    addShopping(product) {
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus!==1){
        ElMessage.error("用户资质还未通过")
        return
      }else {
        this.product = product
        this.showShoppingCar = true
      }
    },
    addShoppingCar(product) {
      product.userId = sessionStorage.getItem("userId");
      axios.post("/api/shoppingCar/addCar", product).then(res => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.showShoppingCar = false
          ElMessage.success('添加成功');
        } else {
          this.showShoppingCar = false
          ElMessage.error(res.data.msg);
        }
      })
    },
    //购买商品
    buyProduct(product) {
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus!==1){
        ElMessage.error("用户资质还未通过")
        return
      }
      this.product = product
      this.showCheckout=true;
      let param = new URLSearchParams();
      param.append("sellPrice",this.product.sellPrice)
      param.append("discount",this.product.discount)
      param.append("userDiscount",sessionStorage.getItem("userDiscount"))
      axios.post("/api/goods/getMoney",param).then(res=>{
        console.log(res.data)
        this.moneyVo = res.data
      })
    },
    pay(payMethod){
      console.log(JSON.stringify(this.ackAddress))
      let param = new URLSearchParams();
      param.append("buyNum",this.buyNum)
      param.append("userId",sessionStorage.getItem("userId"))
      param.append("userNo",sessionStorage.getItem("userNo"))
      param.append("payMethod",payMethod)
      param.append("address",JSON.stringify(this.ackAddress))
      param.append("buyDtoStr",JSON.stringify(this.product))
      param.append("userDiscount",sessionStorage.getItem("userDiscount"))
      param.append("totalPrice",this.moneyVo.totalPrice)
      param.append("totalMoney",this.moneyVo.totalMoney)
      param.append("preTotalPrice",this.moneyVo.preTotalPrice)
      console.log(param)
      axios.post("/api/goods/buy",param).then(res=>{
        if(res.data.code===200){
          if(payMethod===0){
            console.log(res.data)
            window.open("/api/pay/alipay/"+res.data.data.orderNo+"/"+res.data.data.totalPrice+"/"+sessionStorage.getItem("userId")+"")
          }
          ElMessage.success(res.data.msg)
        }else {
          ElMessage.error(res.data.msg)
        }
      })
      this.closeDiv();
    },
    //关闭dialog
    closeDiv() {
      this.product = {}
      this.showShoppingCar = false
      this.showCheckout = false
    },
    toShoppingCar(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('shoppingCar')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },
    toOrder(){
      let str = sessionStorage.getItem("user")
      let user = JSON.parse(str)
      console.log(user)
      if(user.auditStatus===1){
        this.$router.push('order')
      }else{
        ElMessage.error("用户资质还未通过")
      }
    },
    // //跳转购物车
    // toCar() {
    //   this.$router.push('shoppingCar')
    // },
    // //跳转个人订单
    // toOrder() {
    //   this.$router.push('order')
    // },
    // //跳转个人信息
    // toUser() {
    //   this.$router.push('user')
    // },
    // //跳转退款订单管理
    // toReturnOrder() {
    //   this.$router.push('returnOrder')
    // },
    // //跳转预存款管理
    // toUserMoney() {
    //   this.$router.push('userMoney')
    // },
    //查询收货地址
    queryAddress() {
      axios.get('api/address/queryAddress?userNo=' + sessionStorage.getItem('userNo')).then(p => {
        if (p.data.code === 200) {
          this.addressOptions = p.data.data;
          for (let i = 0; i < this.addressOptions.length; i++) {
            if (this.addressOptions[i].defaultAddress === 1) {
              this.selectAddress = this.addressOptions[i].addressId;
              this.ackAddress = this.addressOptions[i];
              break;
            }
          }
        } else {
          ElMessage.error(p.data.msg);
        }

      })
    },
    changeAddress() {
      for (let i = 0; i < this.addressOptions.length; i++) {
        if (this.addressOptions[i].addressId === this.selectAddress) {
          this.ackAddress = this.addressOptions[i];
          break;
        }
      }
      console.log(this.ackAddress)
    }
  }
}
</script>
<style>
#headDiv {
  width: 100%;
  background-color: white;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 5px 10px gray;
}

#bodyDiv {
  width: 1400px;
  padding: 20px;
  margin: 0;
  /*box-shadow: 0 0 10px gray;
  background-color: white;*/
}

.el-carousel__item h3 {
  display: flex;
  color: #475669;
  opacity: 0.8;
}

</style>
